<template>
  <div class="app-shell">
    <main class="page-main layout">
      <LeftSidebar 
        :user="userStore.currentUser" 
        @logout="onLogout" 
        @view-profile="onViewProfile" 
        @new-chat="onNewChat"
        @select-conversation="onSelectConversation"
        @delete-conversation="onDeleteConversation"
        @toggle="onSidebarToggle"
      />
      <section class="layout__chat">
        <ChatRoom />
      </section>
    </main>
    
    <UserProfileDialog 
      :visible="profileDialogVisible" 
      :user="userStore.currentUser" 
      @close="profileDialogVisible = false" 
    />
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../stores/user';
import { chatApi } from '../services/chat';
import ChatRoom from './ChatRoom.vue';
import LeftSidebar from '../components/LeftSidebar.vue';
import UserProfileDialog from '../components/UserProfileDialog.vue';
import { useConversationStore } from '../stores/conversation';

const conversationStore = useConversationStore();
const router = useRouter();
const userStore = useUserStore();

const profileDialogVisible = ref(false);

async function onLogout() {
  try {
    await userStore.logout();
    router.push('/login');
  } catch (error) {
    console.error('登出失败:', error);
    alert('登出失败，请重试');
  }
}

function onViewProfile() {
  profileDialogVisible.value = true;
}

/**
 * 开启新对话：跳转到聊天界面
 */
function onNewChat() {
  // TODO: 清空当前对话，开始新对话
  console.log('开始新对话');
  router.push('/')
}

function onSidebarToggle(collapsed) {
  console.log('侧边栏状态:', collapsed ? '收起' : '展开');
}

function onSelectConversation(chatId) {
  // 跳转路由，携带 chatId 查询参数，ChatRoom 会基于路由加载历史
  if (!chatId) return;
  router.replace({ path: '/', query: { chatId: String(chatId) } });
}

function onDeleteConversation(chatId) {
  if (!chatId) return;
  if (confirm('您确定要删除这个对话吗？')) {
    //根据对话 ID 删除对应的对话历史
    const result = chatApi.deleteChatHistory(chatId);
    if(result){
      alert('删除成功');
      //重新加载侧边栏中的对话历史列表
      const uid = userStore.currentUser?.id;
      if (uid) {
        conversationStore.loadConversations(uid);
      }
    }
  }
  
}
</script>

<style scoped>
.app-shell { min-height: 100vh; display: flex; flex-direction: column; }
.page-main { flex: 1; }
.layout { display: grid; grid-template-columns: 170px 1fr; }
.layout__chat { min-width: 0; }
@media (max-width: 1024px) { .layout { grid-template-columns: 64px 1fr; } }
</style>
